package org.zwy.gradetrack.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zwy.gradetrack.entity.Course;
import org.zwy.gradetrack.entity.CourseScore;
import org.zwy.gradetrack.entity.Graduate;
import org.zwy.gradetrack.entity.DirectEvaluation;
import org.zwy.gradetrack.entity.CourseGoalAchievement;
import org.zwy.gradetrack.entity.CourseSupportMatrix;
import org.zwy.gradetrack.entity.Teacher;
import org.zwy.gradetrack.mapper.CourseScoreMapper;
import org.zwy.gradetrack.mapper.CourseGoalAchievementMapper;
import org.zwy.gradetrack.mapper.CourseSupportMatrixMapper;
import org.zwy.gradetrack.service.CourseScoreService;
import org.zwy.gradetrack.service.CourseService;
import org.zwy.gradetrack.service.GraduateService;
import org.zwy.gradetrack.service.DirectEvaluationService;
import org.zwy.gradetrack.service.TeacherService;
import org.zwy.gradetrack.vo.CourseScoreVo;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 课程得分Service实现类
 */
@Service
public class CourseScoreServiceImpl extends ServiceImpl<CourseScoreMapper, CourseScore> implements CourseScoreService {

    private static final Logger logger = LoggerFactory.getLogger(CourseScoreServiceImpl.class);

    @Autowired
    private CourseService courseService;

    @Autowired
    private GraduateService graduateService;

    @Autowired
    private DirectEvaluationService directEvaluationService;

    @Autowired
    private CourseGoalAchievementMapper courseGoalAchievementMapper;

    @Autowired
    private CourseSupportMatrixMapper courseSupportMatrixMapper;

    @Autowired
    private TeacherService teacherService;

    @Override
    @Transactional
    public CourseScore saveOrUpdateScore(CourseScore courseScore) {
        logger.info("开始保存或更新课程得分: {}", courseScore);
        
        // 检查课程是否存在
        Course course = courseService.getById(courseScore.getCourseId());
        if (course == null) {
            logger.error("课程不存在，courseId: {}", courseScore.getCourseId());
            throw new RuntimeException("课程不存在");
        }

        // 检查毕业生是否存在
        if (!graduateService.lambdaQuery()
                .eq(Graduate::getId, courseScore.getGraduateId())
                .exists()) {
            logger.error("毕业生不存在，graduateId: {}", courseScore.getGraduateId());
            throw new RuntimeException("毕业生不存在");
        }

        // 设置时间
        LocalDateTime now = LocalDateTime.now();
        if (courseScore.getId() == null) {
            courseScore.setCreateTime(now);
        }
        courseScore.setUpdateTime(now);

        // 保存或更新课程得分
        this.saveOrUpdate(courseScore);
        logger.info("课程得分保存或更新成功: {}", courseScore);

        // --- 联动更新或插入 DirectEvaluation --- //
        // 确保传递给辅助方法的 course.getId() 是 Integer 类型，如果 DirectEvaluation 实体中 courseId 是 Integer
        updateDirectEvaluationsForCourse(course.getId().intValue());
        
        return courseScore;
    }

    @Override
    public List<CourseScoreVo> getStudentCourseScores(Long graduateId, String courseCode, String courseName, String courseType) {
        logger.info("开始获取课程得分列表，graduateId: {}, courseCode: {}, courseName: {}, courseType: {}",
                graduateId, courseCode, courseName, courseType);
        List<CourseScoreVo> scores = baseMapper.getStudentCourseScoresWithDetails(graduateId, courseCode, courseName, courseType);
        logger.info("查询到的课程得分记录数: {}", scores.size());
        return scores;
    }

    /**
     * 辅助方法：更新指定课程的所有直接评价
     * @param courseId 课程ID (Integer类型)
     */
    @Transactional
    public void updateDirectEvaluationsForCourse(Integer courseId) {
        // 1. 获取课程的目标达成度信息 (学年, 学期, 达成度)
        CourseGoalAchievement latestAchievement = courseGoalAchievementMapper.getLatestAchievementByCourse(courseId);
        if (latestAchievement == null) {
            logger.warn("未找到课程 {} 的课程目标达成度信息，无法更新直接评价。", courseId);
            return;
        }
        Integer academicYear = latestAchievement.getAcademicYear();
        Integer semester = latestAchievement.getSemester();

        // 2. 获取评价教师ID (简单获取该课程所属专业的一个教师作为评价人)
        Course course = courseService.getById(courseId.longValue()); // courseService.getById 期望 Long
        if (course == null || course.getMajorId() == null) {
            logger.warn("无法获取课程 {} 的专业信息，无法确定评价人。", courseId);
            return;
        }
        LambdaQueryWrapper<Teacher> teacherWrapper = new LambdaQueryWrapper<>();
        teacherWrapper.eq(Teacher::getMajorId, course.getMajorId()).last("LIMIT 1");
        Teacher evaluator = teacherService.getOne(teacherWrapper);
        Integer evaluatorId = (evaluator != null) ? evaluator.getId() : null;

        if (evaluatorId == null) {
            logger.warn("未找到课程 {} 所属专业的评价教师，直接评价将没有评价人ID。", courseId);
        }

        // 3. 获取该课程对所有指标点的支撑权重
        List<CourseSupportMatrix> supportMatrices = courseSupportMatrixMapper.getSupportMatrixByCourseId(courseId);
        if (supportMatrices.isEmpty()) {
            logger.warn("未找到课程 {} 的指标点支撑矩阵信息，无法更新直接评价。", courseId);
            return;
        }

        for (CourseSupportMatrix matrix : supportMatrices) {
            Integer indicatorId = matrix.getIndicatorId();
            
            // 查找或创建 DirectEvaluation 记录
            LambdaQueryWrapper<DirectEvaluation> directEvalWrapper = new LambdaQueryWrapper<>();
            directEvalWrapper.eq(DirectEvaluation::getCourseId, courseId)
                             .eq(DirectEvaluation::getIndicatorId, indicatorId)
                             .eq(DirectEvaluation::getAcademicYear, academicYear)
                             .eq(DirectEvaluation::getSemester, semester);
            DirectEvaluation directEvaluation = directEvaluationService.getOne(directEvalWrapper);
            
            if (directEvaluation == null) {
                directEvaluation = new DirectEvaluation();
                directEvaluation.setCourseId(courseId);
                directEvaluation.setIndicatorId(indicatorId);
                directEvaluation.setAcademicYear(academicYear);
                directEvaluation.setSemester(semester);
                directEvaluation.setDataSource("课程考核"); // 默认数据来源
                directEvaluation.setEvaluationStatus("初稿"); // 默认评价状态
                directEvaluation.setEvaluationTime(LocalDateTime.now());
                directEvaluation.setCreateTime(LocalDateTime.now());
            }
            
            // 设置从 CourseGoalAchievement 和 CourseSupportMatrix 获取的字段
            directEvaluation.setGoalAchievement(latestAchievement.getGoalAchievement());
            directEvaluation.setSupportWeight(matrix.getWeight());
            directEvaluation.setEvaluatorId(evaluatorId);
            directEvaluation.setUpdateTime(LocalDateTime.now());

            // 调用 DirectEvaluationService 来计算 studentCount, avgScore, passRate, evaluationScore
            directEvaluationService.calculateEvaluationMetrics(directEvaluation);
            
            // 保存或更新 DirectEvaluation
            directEvaluationService.saveOrUpdate(directEvaluation);
            logger.info("已更新或创建 DirectEvaluation: courseId={}, indicatorId={}, academicYear={}, semester={}",
                    courseId, indicatorId, academicYear, semester);
        }
    }
} 